package com.xb;

import com.xb.Entity.User;
import com.xb.util.dbUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 事务的隔离级别
 */
public class TransactionTest02 {

    @Test
    public void testSelect() throws SQLException {
        //获取连接
        Connection connection = dbUtil.getConnection();
        connection.setAutoCommit(false);
        connection.setTransactionIsolation(2); //设置隔离级别为读未提交
        //获取他的隔离级别
        /**
         * int TRANSACTION_READ_UNCOMMITTED = 1;
         *int TRANSACTION_READ_COMMITTED = 2;
         *int TRANSACTION_REPEATABLE_READ = 4;
         *int TRANSACTION_SERIALIZABLE = 8;
         */
        System.out.println(connection.getTransactionIsolation());
        /**
         * 在TRANSACTION_READ_UNCOMMITTED的情况下：
         *      第一次读取到是 4000 修改后再读 User{user='CC', password='abcd', balance=5000} 发现是5000 但是他事务还没提交的
         *      再去读取User{user='CC', password='abcd', balance=4000}
         * 在TRANSACTION_READ_COMMITTED 的情况下
         *      首先查的是4000 在更新但是还没提交的时候再去读取User{user='CC', password='abcd', balance=4000}的时候还是4000
         *      但是等更新提交后再去读取就是User{user='CC', password='abcd', balance=5000}
         * 在TRANSACTION_REPEATABLE_READ的情况下：
         *      一开始读取的就是User{user='CC', password='abcd', balance=4000} 在修改更新结束后还是User{user='CC', password='abcd', balance=4000}
         *      只有这个事务提交后再去读就是User{user='CC', password='abcd', balance=5000}
         */
        String sql = "SELECT * FROM user_table where user = ?";
        List<User> list = dbUtil.selectGetDataBytrasaction(connection, sql, User.class, "CC");
        list.forEach(System.out::println);
    }
    @Test
    public void testUpdate() throws SQLException {
        //获取连接
        Connection connection = dbUtil.getConnection();
        connection.setAutoCommit(false);
        String sql = "UPDATE user_table SET balance = ? where user = ?";
        dbUtil.DmlSqlByTransaction(connection,sql,"5000","CC");
        System.out.println("修改成功");
        try {
            Thread.sleep(15000);
            connection.commit();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
